<template>
  <view class="move-container">
    <view class="form-section">
      <view class="form-item">
        <text class="label">地码:</text>
        <input
            v-model="formData.fromLocation"
            class="input"
            type="text"
            placeholder="请扫描或输入地码"
        />
      </view>
      <view class="form-item">
        <text class="label">条码:</text>
        <view class="barcode-input-row">
          <input
              v-model="barcodeInput"
              class="input"
              type="text"
              placeholder="请扫描条码"
              @confirm="handleBarcodeInputAuto"
              :focus="true"
          />
          <view class="barcode-count" @click="showBarcodeList = true">
            {{ formData.barcodes.length }}
          </view>
        </view>
      </view>
      <view class="form-item">
        <text class="label">路线号:</text>
        <input
            v-model="formData.routeNo"
            class="input"
            type="text"
            placeholder="请输入路线号"
        />
      </view>
      <view class="form-item">
        <text class="label">到货日期:</text>
        <input
            v-model="formData.arrivalDate"
            class="input"
            type="date"
            :value="formData.arrivalDate"
            @input="onDateChange"
        />
      </view>
      <view class="form-item">
        <text class="label">物料简称:</text>
        <input
            v-model="formData.materialName"
            class="input"
            type="text"
            placeholder="请输入物料简称"
        />
      </view>
      <view class="btn-group">
        <button @click="handleReset" class="btn btn-default">重置</button>
        <button @click="handleSubmit" class="btn btn-primary" :disabled="loading">
          <text v-if="loading" class="cuIcon-loading2 iconfont-spin"></text>
          {{ loading ? '提交中...' : 'KTL入库' }}
        </button>
      </view>
      <!-- 条码列表弹窗 -->
      <view v-if="showBarcodeList" class="barcode-list-modal">
        <view class="barcode-list-content">
          <view class="barcode-list-title">已扫条码</view>
          <view v-for="(code, idx) in formData.barcodes" :key="idx" class="barcode-item">
            <text>{{ code }}</text>
            <button @click="removeBarcode(idx)" class="remove-btn">删除</button>
          </view>
          <button @click="showBarcodeList = false" class="close-btn">关闭</button>
        </view>
      </view>
    </view>
    <!-- 扫描条码展示区域 -->
    <view v-if="formData.barcodes.length" class="barcode-display-list">
      <view v-for="(code, idx) in formData.barcodes" :key="idx" class="barcode-display-item">
        {{ code }}
      </view>
    </view>
  </view>
</template>

<script>
import { moveStock, rkStock } from '@/api/system/stock';

var main, receiver, filter;

export default {
  data() {
    return {
      formData: {
        barcodes: [],
        routeNo: '',
        arrivalDate: '',
        materialName: '',
        fromLocation: ''
      },
      barcodeInput: '',
      showBarcodeList: false,
      loading: false
    };
  },

  onLoad() {
    // 默认到货日期为今天
    const today = new Date();
    const yyyy = today.getFullYear();
    const mm = String(today.getMonth() + 1).padStart(2, '0');
    const dd = String(today.getDate()).padStart(2, '0');
    this.formData.arrivalDate = `${yyyy}-${mm}-${dd}`;
    this.initScan();
  },

  onShow() {
    this.startScan();
  },

  onHide() {
    this.stopScan();
  },

  onUnload() {
    this.stopScan();
  },

  methods: {
    initScan() {
      let _this = this;
      /* #ifdef APP-PLUS */
      main = plus.android.runtimeMainActivity();
      var IntentFilter = plus.android.importClass('android.content.IntentFilter');
      filter = new IntentFilter();
      filter.addAction("com.service.scanner.data")
      receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
        onReceive: function (context, intent) {
          plus.android.importClass(intent);
          let code = intent.getStringExtra("ScanCode");
          _this.handleScanResult(code);
        }
      });
      /* #endif */
    },

    startScan() {
      /* #ifdef APP-PLUS */
      main && receiver && filter && main.registerReceiver(receiver, filter);
      /* #endif */
    },

    stopScan() {
      /* #ifdef APP-PLUS */
      main && receiver && main.unregisterReceiver(receiver);
      /* #endif */
    },

    // 处理扫码结果
    handleScanResult(code) {
      if (!code) return;
      let trimmedCode = code.trim();
      if (!trimmedCode) return;

      // 新增：如果条码位数大于22位，截取第一个*符号之前的数据
      if (trimmedCode.length > 22) {
        const asteriskIndex = trimmedCode.indexOf('*');
        if (asteriskIndex !== -1) {
          trimmedCode = trimmedCode.substring(0, asteriskIndex);
        }
      }

      // 判断是否已存在
      if (this.formData.barcodes.includes(trimmedCode)) {
        uni.showToast && uni.showToast({
          title: '该条码已扫描',
          icon: 'none',
          duration: 1500
        });
        return;
      }
      this.formData.barcodes.push(trimmedCode);
      // 触发视图更新（理论上push已响应式，这里保险起见）
      this.formData.barcodes = this.formData.barcodes.slice();
      this.barcodeInput = '';
    },

    // 重置表单
    handleReset() {
      this.formData.barcodes = [];
      this.formData.routeNo = '';
      this.formData.arrivalDate = '';
      this.formData.materialName = '';
      this.formData.fromLocation = '';
      this.barcodeInput = '';
      // 重新设置默认日期
      const today = new Date();
      const yyyy = today.getFullYear();
      const mm = String(today.getMonth() + 1).padStart(2, '0');
      const dd = String(today.getDate()).padStart(2, '0');
      this.formData.arrivalDate = `${yyyy}-${mm}-${dd}`;
    },

    // 提交表单
    handleSubmit() {
      if (this.loading) return;
      if (!this.formData.barcodes.length) {
        this.$modal && this.$modal.msgError
            ? this.$modal.msgError('请扫描或输入条码')
            : uni.showToast({ title: '请扫描或输入条码', icon: 'none' });
        return;
      }
      if (!this.formData.fromLocation) {
        this.$modal && this.$modal.msgError
            ? this.$modal.msgError('请输入或扫描地码')
            : uni.showToast({ title: '请输入或扫描地码', icon: 'none' });
        return;
      }
      if (!this.formData.arrivalDate) {
        this.$modal && this.$modal.msgError
            ? this.$modal.msgError('请选择到货日期')
            : uni.showToast({ title: '请选择到货日期', icon: 'none' });
        return;
      }
      this.loading = true;
      rkStock(this.formData)
          .then(res => {
            if (res.code === 200) {
              this.$modal && this.$modal.msgSuccess
                  ? this.$modal.msgSuccess('提交成功')
                  : uni.showToast({ title: '提交成功', icon: 'success' });
              this.handleReset();
            } else {
              this.$modal && this.$modal.msgError
                  ? this.$modal.msgError(res.msg || '提交失败')
                  : uni.showToast({ title: res.msg || '提交失败', icon: 'none' });
            }
          })
          .catch(error => {
            console.error('提交失败:', error);
            this.$modal && this.$modal.msgError
                ? this.$modal.msgError('提交失败，请稍后重试')
                : uni.showToast({ title: '提交失败，请稍后重试', icon: 'none' });
          })
          .finally(() => {
            this.loading = false;
          });
    },

    handleBarcodeInputAuto(e) {
      console.log("111"+e)
      let inputVal = e.detail.value.trim();
      this.barcodeInput = inputVal;

      if (!inputVal || inputVal.length < 6) return;

      // 新增：如果条码位数大于22位，截取第一个*符号之前的数据
      if (inputVal.length > 22) {
        const asteriskIndex = inputVal.indexOf('*');
        if (asteriskIndex !== -1) {
          inputVal = inputVal.substring(0, asteriskIndex);
        }
      }

      if (this.formData.barcodes.includes(inputVal)) {
        uni.showToast({ title: '该条码已扫描', icon: 'none' });
        this.barcodeInput = '';
        return;
      }
      if (this.formData.barcodes.includes(inputVal)) {
        uni.showToast && uni.showToast({
          title: '该条码已扫描',
          icon: 'none',
          duration: 1500
        });
        this.barcodeInput = '';
        return;
      }
      this.formData.barcodes.push(inputVal);
      this.formData.barcodes = this.formData.barcodes.slice();
      console.log('222222')
      this.barcodeInput = '';
    },

    removeBarcode(idx) {
      this.formData.barcodes.splice(idx, 1);
      // 触发视图更新（保险起见）
      this.formData.barcodes = this.formData.barcodes.slice();
    },

    onDateChange(e) {
      this.formData.arrivalDate = e.target.value;
    }
  }
}
</script>

<style lang="scss" scoped>
.move-container {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding: 16px;
}

.form-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  .form-item {
    margin-bottom: 16px;
    .label {
      display: block;
      font-size: 14px;
      color: #333;
      margin-bottom: 8px;
      font-weight: 500;
      .required {
        color: #ff4d4f;
        margin-left: 4px;
      }
    }
    .input {
      width: 100%;
      height: 40px;
      background-color: #f8f9fa;
      border-radius: 4px;
      padding: 0 12px;
      font-size: 14px;
      color: #333;
    }
  }
}

.btn-group {
  display: flex;
  justify-content: space-between;
  margin-top: 24px;
  .btn {
    width: 48%;
    height: 40px;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;
    &.btn-default {
      background-color: #f8f9fa;
      color: #666;
    }
    &.btn-primary {
      background-color: #4A90E2;
      color: #fff;
      &:disabled {
        opacity: 0.7;
      }
    }
  }
}

.iconfont-spin {
  display: inline-block;
  animation: loading-rotate 2s linear infinite;
}

@keyframes loading-rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.barcode-input-row {
  display: flex;
  align-items: center;
  .input {
    flex: 1;
    margin-right: 8px;
  }
  .barcode-count {
    min-width: 32px;
    height: 32px;
    background: #ff4d4f;
    color: #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
    font-weight: bold;
    cursor: pointer;
    border: 2px solid #fff;
    box-shadow: 0 0 0 2px #ff4d4f;
  }
}

.barcode-list-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.barcode-list-content {
  background: #fff;
  border-radius: 16px;
  padding: 32px 28px 24px 28px;
  width: 320px;
  min-height: 340px;
  max-height: 400px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  justify-content: flex-start;
}

.barcode-list-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 24px;
  text-align: center;
}

.barcode-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  min-height: 38px;
}

.barcode-item text {
  font-size: 16px;
  color: #222;
  flex: 1;
  text-align: left;
  word-break: break-all;
}

.remove-btn {
  background: #ff4d4f;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 0 14px;
  font-size: 14px;
  margin-left: 16px;
  height: 32px;
  line-height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn {
  width: 100%;
  height: 44px;
  background: #4A90E2;
  color: #fff;
  border: none;
  border-radius: 8px;
  margin-top: 28px;
  font-size: 17px;
  font-weight: 500;
}

/* 下方条码展示区域样式 */
.barcode-display-list {
  margin: 24px 0 0 0;
  padding: 0 8px;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.barcode-display-item {
  background: none;
  border: none;
  color: #222;
  font-size: 14px;
  text-align: center;
  border-radius: 0;
  margin-bottom: 0;
  padding: 0;
  font-weight: normal;
}
</style>